package com.woniu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

/**
 * @author: 16327
 * @date: 2020/12/28 14:07
 * @description:
 */
@Controller
@RequestMapping("file")
public class FileController {
    @RequestMapping("upload")
    public String fileUpLoad(MultipartFile file, HttpServletRequest request) throws IOException {
        long size = file.getSize();
        if (size>1048576.0){
            System.out.println("文件字节是"+size+",太大了");
            throw new RuntimeException("文件太大了");
        }
        String realPath = request.getServletContext().getRealPath("/");
        File dir = new File(realPath,"img");
        String s = UUID.randomUUID().toString();
        String originalFilename = file.getOriginalFilename();
        int i = 0;
        if (originalFilename != null) {
            i = originalFilename.lastIndexOf('.');
        }
        String substring = null;
        if (originalFilename != null) {
            substring = originalFilename.substring(i);
        }
        String localDate = LocalDate.now().toString();
        File file1 = new File(dir,localDate);
        if (!file1.exists()){
            file1.mkdir();
        }
        file.transferTo(new File(file1,s+substring));
        return "c";
    }
}
